package controllers

import (
	"exchangeapp/global"
	"exchangeapp/models"
	"github.com/gin-gonic/gin"
	"net/http"
)

func AddStudent(ctx *gin.Context) {
	var student struct {
		CardId      string
		Name        string
		Gender      string
		Age         string
		Address     string
		PhoneNumber string
	}

	if err := ctx.ShouldBindJSON(&student); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	var stu models.Student
	stu.CardId = student.CardId
	stu.Name = student.Name
	stu.Gender = student.Gender
	stu.Age = student.Age
	stu.Address = student.Address
	stu.PhoneNumber = student.PhoneNumber

	if err := global.DB.AutoMigrate(&stu); err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	if err := global.DB.Create(&stu).Error; err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{"message": "bingo"})
}

func SearchAllStudent(ctx *gin.Context) {
	var students []models.Student
	if err := global.DB.Find(&students).Error; err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{"message": students})
}
